package com.woniuxy.ai.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.woniuxy.ai.entity.Faq;
import com.woniuxy.ai.service.FaqService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/faq")
@CrossOrigin
public class FaqController {

    @Autowired
    private FaqService faqService;

    // 分页查询 FAQ
    @GetMapping("/page")
    public Page<Faq> getFaqPage(
            @RequestParam(defaultValue = "1") int pageNum,
            @RequestParam(defaultValue = "10") int pageSize) {
        return faqService.page(new Page<>(pageNum, pageSize));
    }

    // 按关键词搜索并分页
    @GetMapping("/search")
    public Page<Faq> searchFaqs(
            @RequestParam String keyword,
            @RequestParam(defaultValue = "1") int pageNum,
            @RequestParam(defaultValue = "10") int pageSize) {
        return faqService.page(new Page<>(pageNum, pageSize),
                new QueryWrapper<Faq>().like("question", keyword));
    }

    // 获取所有FAQ
    @GetMapping
    public List<Faq> getAllFaqs() {
        return faqService.list();
    }

    // 根据ID获取FAQ
    @GetMapping("/{id}")
    public Faq getFaqById(@PathVariable Long id) {
        return faqService.getById(id);
    }

    // 新增FAQ
    @PostMapping
    public boolean addFaq(@RequestBody Faq faq) {
        return faqService.save(faq);
    }

    // 更新FAQ
    @PutMapping("/{id}")
    public boolean updateFaq(@PathVariable Long id, @RequestBody Faq faq) {
        faq.setId(Math.toIntExact(id));
        return faqService.updateById(faq);
    }

    // 删除FAQ
    @DeleteMapping("/{id}")
    public boolean deleteFaq(@PathVariable Long id) {
        return faqService.removeById(id);
    }

    // 启用/禁用FAQ
    @PostMapping("/toggle/{id}")
    public boolean toggleFaqStatus(@PathVariable Long id) {
        Faq faq = faqService.getById(id);
        faq.setIsActive(faq.getIsActive() == 1 ? 0 : 1);
        return faqService.updateById(faq);
    }

}
